package org.visionlibrary.image.filters.clustering.model;

import java.util.ArrayList;
import java.util.List;

public class Cluster {
	private Centroid centroid;
	private double hQ;
	private List<Sample> bins;
	
	public Cluster(Centroid centroid, double hQ) {
		this.centroid = centroid;
		this.hQ = hQ;
		this.bins = new ArrayList<Sample>();
	}

	public Centroid getCentroid() {
		return centroid;
	}

	public List<Sample> getSamples() {
		return bins;
	}
	
	public boolean add(Sample sample) {
		return bins.add(sample);
	}
	
	public void clear() {
		bins.clear();
	}
	
	public void recalculate() {
		double hijsum = 0;
		double sisum = 0;
		double visum = 0;
		
		for(Sample sample : bins) {
			hijsum += relativeHue(sample.hueIndex);
			sisum += sample.satIndex;
			visum += sample.valIndex;
		}
		
		int hj = (int)Math.floor(hijsum / bins.size());
		int sj = (int)Math.floor(sisum / bins.size());
		int vj = (int)Math.floor(visum / bins.size());
		
		int max = (int) Math.ceil(360/hQ);
		if(hj < 0) {
			hj = max + (hj%max);
		} else if(hj > max) {
			hj = 0 + (hj%max);
		}
		
		centroid = new Centroid(hj, sj, vj);
	}
	
	private double relativeHue(double hi) {
		int hj = centroid.hueIndex;
		if(Math.abs(hi - hj) > (180/hQ) && hj < (180/hQ))
			return hi - (360/hQ);
		
		if(Math.abs(hi - hj) > (180/hQ) && hj > (180/hQ))
			return hi + (360/hQ);
		
		return hi;
	}
}